﻿using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace SvgViewer.Core;

/// <summary>
/// INotifyPropertyChanged 抽象基类
/// </summary>
public abstract class NotifyPropertyBase : INotifyPropertyChanged
{
    /// <summary>
    /// 属性改变通知事件
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;

    /// <summary>
    /// 触发属性改变通知
    /// </summary>
    /// <param name="propertyName">属性名称</param>
    protected virtual void OnPropertyChanged(string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    /// <summary>
    /// 为属性设置值,新值与原值相同时,将不会触发属性改变通知
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="source">原始值</param>
    /// <param name="newValue">新值</param>
    /// <param name="propertyName">属性名</param>
    /// <param name="action">值改变后执行的操作,值未改变将不会执行</param>
    /// <returns>值改变返回 true</returns>
    protected bool SetValue<T>(ref T source, T newValue, string propertyName, Action action = null)
    {
        if (source == null && newValue==null)
        {
            return false;
        }

        if (EqualityComparer<T>.Default.Equals(source, newValue))
        {
            return false;
        }

        source = newValue;
        OnPropertyChanged(propertyName);
        action?.Invoke();
        return true;
    }
}